﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace jmwqz
{
    using HNAC.Weixin.CommonService.CustomMessageHandler;
    using HNAC.Weixin.MP;
    using System.IO;
    using System.Data;
    public partial class weixin : System.Web.UI.Page
    {
        private readonly string Token = "jmvqztoken";//与微信公众账号后台的Token设置保持一致，区分大小写。

        protected void Page_Load(object sender, EventArgs e)
        {
            string signature = Request["signature"];
            string timestamp = Request["timestamp"];
            string nonce = Request["nonce"];
            string echostr = Request["echostr"];

            if (Request.HttpMethod == "GET")
            {
                //get method - 仅在微信后台填写URL验证时触发
                if (CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent(echostr); //返回随机字符串则表示验证通过
                }
                else
                {
                    WriteContent("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, Token));
                }
                Response.End();
            }
            else
            {
                //post method - 当有用户向公众账号发送消息时触发
                //if (!CheckSignature.Check(signature, timestamp, nonce, Token))
                //{
                //    WriteContent("参数错误！");
                //    return;
                //}

                //自定义MessageHandler，对微信请求的详细判断操作都在这里面。
                var messageHandler = new CustomMessageHandler(Request.InputStream, signature, timestamp, nonce);
                
                try
                {
                    if (messageHandler != null && messageHandler.RequestMessage != null && !string.IsNullOrEmpty(messageHandler.RequestMessage.FromUserName))
                    {
                        if (Maticsoft.Common.AppCommon.Instance.CacheFreeOpenids.Contains(messageHandler.RequestMessage.FromUserName))
                        {//缓存中存在该数据,则认为用户是有效,将冻结积分转换为有效积分
                            UpdateFreeze(messageHandler.RequestMessage.FromUserName);
                        }
                    }
                    //测试时可开启此记录，帮助跟踪数据
                    //messageHandler.RequestDocument.Save(
                    //    Server.MapPath("~/App_Data/CacheLog/" + DateTime.Now.Ticks + "_Request_" +
                    //                   messageHandler.RequestMessage.FromUserName + ".txt"));
                    //执行微信处理过程
                    messageHandler.Execute();
                    //测试时可开启，帮助跟踪数据
                    //messageHandler.ResponseDocument.Save(
                    //    Server.MapPath("~/App_Data/CacheLog/" + DateTime.Now.Ticks + "_Response_" +
                    //                   messageHandler.ResponseMessage.ToUserName + ".txt"));
                    if (messageHandler == null || messageHandler.ResponseDocument == null)
                    {
                        WriteContent("");
                        return;
                    }
                    WriteContent(messageHandler.ResponseDocument.ToString());
                    return;
                }
                catch (Exception ex)
                {
                    using (TextWriter tw = new StreamWriter(Server.MapPath("~/App_Data/CacheLog/Error_" + DateTime.Now.Ticks + ".txt")))
                    {
                        tw.WriteLine(ex.Message);
                        tw.WriteLine(ex.StackTrace);
                        //tw.WriteLine(ex.InnerException.Message);
                        if (messageHandler.ResponseDocument != null)
                        {
                            tw.WriteLine(messageHandler.ResponseDocument.ToString());
                        }
                        tw.Flush();
                        tw.Close();
                    }
                    WriteContent("");
                }
                finally
                {
                    Response.End();
                }
            }
        }

        private void WriteContent(string str)
        {
            Response.Output.Write(str);
        }

        /// <summary>
        /// 最简单的Page_Load写法（本方法仅用于演示过程，未实际使用到）
        /// </summary>
        private void MiniProcess()
        {
            string signature = Request["signature"];
            string timestamp = Request["timestamp"];
            string nonce = Request["nonce"];
            string echostr = Request["echostr"];

            if (Request.HttpMethod == "GET")
            {
                //get method - 仅在微信后台填写URL验证时触发
                if (CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent(echostr); //返回随机字符串则表示验证通过
                }
                else
                {
                    WriteContent("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, Token));
                }

            }
            else
            {
                //post method - 当有用户想公众账号发送消息时触发
                if (!CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent("参数错误！");
                }

                //自定义MessageHandler，对微信请求的详细判断操作都在这里面。
                var messageHandler = new CustomMessageHandler(Request.InputStream);
                //执行微信处理过程
                messageHandler.Execute();
                //输出结果
                WriteContent(messageHandler.ResponseDocument.ToString());
            }
            Response.End();
        }

        private bool UpdateFreeze(string openid)
        {
            try
            {
                Maticsoft.Model.tb_userdata muser = GetUserByOpenId(openid);
                if (muser == null)
                {
                    Maticsoft.Common.AppCommon.Instance.DeleteCache(openid);
                    return true;
                }
                Maticsoft.Model.tb_freeze mfreeze = GetFreezeobjByOpenId(muser.id);
                if (mfreeze == null)
                {
                    Maticsoft.Common.AppCommon.Instance.DeleteCache(openid);
                    return true;
                }
                if (mfreeze.state == 0)
                {
                    Maticsoft.Common.AppCommon.Instance.DeleteCache(openid);
                    return true;
                }
                Maticsoft.BLL.tb_freeze bfreeze = new Maticsoft.BLL.tb_freeze();
                mfreeze.state = 0;
                bfreeze.Update(mfreeze);
                
                Maticsoft.BLL.tb_userdata buser = new Maticsoft.BLL.tb_userdata();
                Maticsoft.Model.tb_userdata tjuser = buser.GetModel(mfreeze.tjuer);
                if (tjuser == null)
                {
                    Maticsoft.Common.AppCommon.Instance.DeleteCache(openid);
                    return true;
                }
                if (tjuser.freezejifen >= mfreeze.freezemoney)
                {
                    tjuser.freezejifen -= mfreeze.freezemoney;
                    tjuser.jifen += mfreeze.freezemoney;
                    if (buser.Update(tjuser))
                    {
                        Maticsoft.Common.AppCommon.Instance.LoggerHandler.Log(string.Format("解冻用户积分成功,积分数:{0},用户id:{1}", mfreeze.freezemoney, tjuser.id));
                    }
                    else
                    {
                        Maticsoft.Common.AppCommon.Instance.LoggerHandler.Log(string.Format("解冻用户积分失败,积分数:{0},用户id:{1}", mfreeze.freezemoney, tjuser.id));
                    }
                }
                else
                {
                    tjuser.jifen += (mfreeze.freezemoney - muser.freezejifen);
                    tjuser.freezejifen = 0;
                    if (buser.Update(tjuser))
                    {
                        Maticsoft.Common.AppCommon.Instance.LoggerHandler.Log(string.Format("解冻用户积分成功,积分数:{0},用户id:{1}", mfreeze.freezemoney, tjuser.id));
                    }
                    else
                    {
                        Maticsoft.Common.AppCommon.Instance.LoggerHandler.Log(string.Format("解冻用户积分失败,积分数:{0},用户id:{1}", mfreeze.freezemoney, tjuser.id));
                    }
                }
            }
            catch (System.Exception ex)
            {
                Maticsoft.Common.AppCommon.Instance.LoggerHandler.Log(ex.Message);
                Maticsoft.Common.AppCommon.Instance.LoggerHandler.Log(ex.StackTrace);
                return false;
            }
            finally
            {
                Maticsoft.Common.AppCommon.Instance.DeleteCache(openid);
            }
            return true;
        }

        private Maticsoft.Model.tb_userdata GetUserByOpenId(string openid)
        {
            Maticsoft.BLL.tb_userdata buser = new Maticsoft.BLL.tb_userdata();
            Maticsoft.Model.tb_userdata muser = null;
            try
            {
                DataSet ds = buser.GetList(" wxid='" + openid + "' ");
                if (Maticsoft.Common.Util2.CheckDataSet(ds))
                {
                    DataTable dt = ds.Tables[0];
                    muser = buser.DataTableToList(dt)[0];
                }
            }
            catch (System.Exception ex)
            {
                Maticsoft.Common.AppCommon.Instance.LoggerHandler.Log(ex.Message);
                Maticsoft.Common.AppCommon.Instance.LoggerHandler.Log(ex.StackTrace);
            }

            return muser;
        }

        private Maticsoft.Model.tb_freeze GetFreezeobjByOpenId(int userid)
        {
            Maticsoft.BLL.tb_freeze buser = new Maticsoft.BLL.tb_freeze();
            Maticsoft.Model.tb_freeze muser = null;
            try
            {
                DataSet ds = buser.GetList(" userid='" + userid + "' ");
                if (Maticsoft.Common.Util2.CheckDataSet(ds))
                {
                    DataTable dt = ds.Tables[0];
                    muser = buser.DataTableToList(dt)[0];
                }
            }
            catch (System.Exception ex)
            {
                Maticsoft.Common.AppCommon.Instance.LoggerHandler.Log(ex.Message);
                Maticsoft.Common.AppCommon.Instance.LoggerHandler.Log(ex.StackTrace);
            }

            return muser;
        }
    }
}